package com.bwie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bwie.domain.TbDict;
import com.bwie.mapper.TbDictMapper;
import com.bwie.service.TbDictService;
import com.bwie.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * @author 军哥
 * @version 1.0
 * @description: TODO
 * @date 2024/10/18 13:29
 */

@Service
public class TbDictServiceImpl implements TbDictService {

    @Autowired
    TbDictMapper tbDictMapper;

    @Autowired
    RedisTemplate redisTemplate;

    @PostConstruct
    public void readyDictList() {

        System.out.println("准备字典列表，放入缓存");
        //-- 从数据库中获取字典列表
        String key = "dict_" + 1;
        List<TbDict> list = tbDictMapper.selectList(
                new QueryWrapper<TbDict>().lambda().eq(TbDict::getDictType, 1)
        );

        //-- 把数据存到缓存中
        redisTemplate.delete(key);
        redisTemplate.opsForList().rightPushAll(key, list);
    }

    @Override
    public R getDictList(Integer dictType) {

        //-- 从缓存中 获取 字典列表
        String key = "dict_" + dictType;
        if (redisTemplate.hasKey(key)) {
            System.out.println("从【缓存】中获取字典数据");
            List<TbDict> list = redisTemplate.opsForList().range(key, 0, -1);
            return R.OK(list);
        }

        //-- 缓存中没有，再从数据库中获取
        System.out.println("从【数据库】中获取字典数据");

        List<TbDict> list = tbDictMapper.selectList(
                new QueryWrapper<TbDict>().lambda().eq(TbDict::getDictType, dictType)
        );

        //-- 把数据存到缓存中
        redisTemplate.opsForList().rightPushAll(key, list);

        return R.OK(list);
    }
}
